const router = require('express').Router;
const Person = require('../../../models/person');

// 查询所有
router.get('/', async (req, res) => {
    const data = await Person.find({}).sort({
        _id = -1
    });
    res.json({
        code: 1,
        msg: '查询成功',
        data: data,
    });
});
// 查询一条
router.get('/:id', async (req, res) => {
    try {
        const data = await Person.findById(req.params.id);
        res.json({
            code: 1,
            msg: "获取数据成功",
            data: data,
        });
    } catch (err) {
        res.json({
            code: 0,
            err
        });
    }

});

// 新增存储
router.post('/', async (req, res) => {
    const person = new Person(req.body);
    await person.save();
    res.json({
        code: 1,
        msg: '新增数据成功',
    });
});

// 修改
router.put('/:id', async (req, res) => {
    await Person.findByIdAndUpdate(req.params.id, req.body);
    res.json({
        code: 1,
        msg: "信息修改成功",
    });
});

// 删除
router.delete('/:id', async (req, res) => {
    await Person.findByIdAndDelete(req.params.id);
    res.json({
        code: 1,
        msg: "删除数据成功",
    });
});

module.exports = router;